package com.zjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zjl.Utils.SMSUtils;
import com.zjl.Utils.ValidateCodeUtils;
import com.zjl.common.R;
import com.zjl.entity.User;
import com.zjl.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping(value = "/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession){
        //生成手机号
        String phone = user.getPhone();

        //生成随机4位验证码
            //判空，注意，StringUtils所属包为：org.apache.commons.lang.StringUtils
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //调用阿里云短信发送服务API发送短信
//            SMSUtils.sendMessage(
//                    "签名","模板code","手机号码","参数");
            //将生成的验证码保存到Session
            httpSession.setAttribute(phone,code);

            return R.success("短信发送成功");
        }


        return R.error("短信发送失败");
    }


    /**
     * 接收用户输入的验证码与手机号，进行登录
     * @param map
     * @return
     */
    @PostMapping(value = "/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());
        //获得手机号
        String phone =map.get("phone").toString();
        //获得验证码
        String code = map.get("code").toString();

        //获得session中的验证码
        String codeInSession = session.getAttribute(phone).toString();

        //验证码进行比对
        if (codeInSession!=null&&codeInSession.equals(code)){
            //若比对成功，说明成功登录
                //若为新用户，则新增数据
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(phone!=null,User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
                log.info("新用户,已保存");
            }

            //登录成功，设置session，令过滤器放行
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        //登录失败
        return R.error("登录失败");
    }
}
